﻿using AutoMapper;
using Castle.Components.DictionaryAdapter.Xml;
using CSRedis;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Impl;
using IntelligentAgriculture.Domain.Impl.SheepFileModellmpl;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.IEarTagReposiotry;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using IntelligentAgriculture.Domain.Interface.StartInterface;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace IntelligentAgriculture.Services.StartServices
{
    public class StartService : IStartService
    {
        /// <summary>
        /// 期初仓储
        /// </summary>
        private readonly IStartRepository _startRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<StartService> _logger;

        /// <summary>
        /// 上下文
        /// </summary>
        private readonly AgricultureDbContext _db;

        /// <summary>
        /// 对象关系映射
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// rides
        /// </summary>

        private readonly CSRedis.CSRedisClient _client;
        /// <summary>
        /// 羊只档案仓储
        /// </summary>

        private readonly ISheepFileModelRepository _sheepFileModelRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="startRepository">期初仓储</param>
        /// <param name="logger">日志</param>
        /// <param name="mapper">对象关系映射</param>
        public StartService(IStartRepository startRepository, ILogger<StartService> logger, IMapper mapper,AgricultureDbContext db, ISheepFileModelRepository sheepFileModelRepository)
        {
            _startRepository = startRepository;
            _logger = logger;
            _mapper = mapper;
            _db = db;
            _sheepFileModelRepository = sheepFileModelRepository;
            _client = new CSRedis.CSRedisClient("127.0.0.1:6379");
         
          
        }


   

        /// <summary>
        /// 显示查询期初表
        /// </summary>
        /// <param name="input">输入参数</param>
        /// <returns>返回数据</returns>
        public async Task<PageOutput<StartOutput>> GetStartList(StartInput input)
        {
            try
            {
                //从redis获取数据
                var startlist = _client.Get<List<Start>>("getStart");
                if (startlist == null)
                {
                    //如果没有，则从数据库获取数据
                    startlist = _db.Starts.Where(c => c.Isdel==false).ToList();
                    // 将数据存入Redis，缓存时间待定，例如设置有效期为30分钟
                    _client.Set("getStart", startlist, TimeSpan.FromMinutes(30));
                }
                _logger.LogInformation("这是显示查询期初表");


                var list = await _startRepository.GetStartList();

                var filteredList = (from start in list
                                    join eartag in _db.Sheepfilemodels on start.EarTag equals eartag.EarTag
                                    join ridgepole in _db.Ridgepoles on start.RidgepoleId equals ridgepole.RidgepoleId
                                    join column in _db.Columnmanagements on start.ColumnManagementId equals column.ColumnManagementId
                                    where (input.Type <= 0 || start.Type == input.Type)  // 筛选当前类型羊数据
                                    select new StartOutput
                                    {
                                        ColumnManagementId = column.ColumnManagementId,
                                        ColumnName = column.ColumnName,
                                        CreateDate = start.CreateDate,
                                        CreateName = start.CreateName,
                                        DocumentNumber = start.DocumentNumber,
                                        EarTag = eartag.EarTag,
                                        OnlyNumber = start.OnlyNumber,
                                        Remark = start.Remark,
                                        OpeningDate = start.OpeningDate,
                                        ReplantingDate = start.ReplantingDate,
                                        RidgepoleId = start.RidgepoleId,
                                        RidgepoleName = ridgepole.RidgepoleName,
                                        StartId = start.StartId,
                                        Stage = start.Stage,
                                        Type = start.Type,
                                        UpdateName = start.UpdateName,
                                        UpdateDate = start.UpdateDate,
                                        Weight = start.Weight,
                                    }).ToList();

                // 应用额外的筛选条件
                if (!string.IsNullOrEmpty(input.EarTag))
                {
                    filteredList = filteredList.Where(c => c.EarTag.Contains(input.EarTag)).ToList();
                }
                if (!string.IsNullOrEmpty(input.Sdate))
                {
                    var startDate = DateTime.Parse(input.Sdate);
                    filteredList = filteredList.Where(c => c.ReplantingDate >= startDate).ToList();
                }
                if (!string.IsNullOrEmpty(input.Edate))
                {
                    var endDate = DateTime.Parse(input.Edate).AddDays(1);
                    filteredList = filteredList.Where(c => c.ReplantingDate < endDate).ToList();
                }


                // 分页处理
                var pagedData = filteredList.OrderByDescending(c => c.StartId)
                                            .Skip((input.PageIndex - 1) * input.PageSize)
                                            .Take(input.PageSize)
                                            .ToList();

                var result = new PageOutput<StartOutput>
                {
                    TotalCount = filteredList.Count(), // 计算筛选后的总条数
                    PageSize = input.PageSize,
                    Data = _mapper.Map<List<StartOutput>>(pagedData)
                };

             

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError("显示查询期初表发生异常：" + ex.Message);
                throw;
            }
        }




        /// <summary>
        /// 批量添加期初表数据
        /// </summary>
        /// <param name="inputs">实体列表</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> AddStartAsync(List<Start> inputs)
        {
            // 为每个输入项设置创建相关的属性
            foreach (var input in inputs)
            {
                input.CreateDate = DateTime.Now;
                input.CreateName = "Admin";
                input.DocumentNumber = YitIdHelper.NextId().ToString();
                input.OpeningDate = DateTime.Now;
                input.UpdateDate = DateTime.Now;
                input.UpdateName = "张三";
                input.Isdel = false;
            }

            // 批量添加期初表数据
            await _startRepository.AddStartAsync(inputs);

            // 处理与羊只档案的关联和更新
            foreach (var input in inputs)
            {
                var sheep = await _sheepFileModelRepository.GetSheepfilemodels();
                var sheeplist = sheep.FirstOrDefault(c => c.EarTag == input.EarTag);

                if (sheeplist != null)
                {
                    // 更新羊只档案数据
                    sheeplist.BuildingId = input.RidgepoleId;
                    sheeplist.ColumnId = input.ColumnManagementId;
                    sheeplist.Growthstage = input.Stage;
                    sheeplist.PresentState = 1;

                    // 保存更新后的羊只档案数据
                    await _sheepFileModelRepository.UpdaSheepFileModel(sheeplist);
                }
            }

            return inputs.Count;
        }


        /// <summary>
        /// 逻辑删除期初数据
        /// </summary>
        /// <param name="startId">主键id</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> DeleteStart(int startId)
        {
            return await _startRepository.DeleteStart(startId);
        }


        /// <summary>
        /// 批量逻辑删除期初表
        /// </summary>
        /// <param name="startIds">id</param>
        /// <returns>返回数据</returns>
        public async Task<int> DeleteRangeStart(IEnumerable<int> startIds)
        {
            return await _startRepository.DeleteRangeStart(startIds);
        }

        /// <summary>
        /// 反填期初表
        /// </summary>
        /// <param name="startId">主键id</param>
        /// <returns>返回数据</returns>
        public async Task<StartOutput> GetStartByIdAsync(int startId)
        {
            var start = await _startRepository.GetByIdAsync(startId); 

            if (start == null)
            {
                return null; 
            }

            var startOutput = _mapper.Map<StartOutput>(start);

            return startOutput;
        }

        /// <summary>
        /// 修改期初表
        /// </summary>
        /// <param name="input">期初实体</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> UpdateStartAsync(Start input)
        {
            var list = _mapper.Map<Start>(input);
            return await _startRepository.UpdateAsync(list);
        }

     
    }
}
